

function doUrlRequest(url, onSuccess) {
    var xhr = new XMLHttpRequest();
    try {
        xhr.onreadystatechange = onSuccess;

        xhr.onerror = function(error) {
            console.debug(error);
        }

        xhr.open("GET", url, true);
        xhr.send(null);
    } 
	catch(e) {
        console.error(e);
    }
}

function parseWebsites() {
	var onWebsiteDataRetrieval = function() {
		if (this.readyState == 4) {
			// need to kill it here. called multiple times. bug in chrome
		//	delete onWebsiteDataRetrieval;
		
		
		
		/*client.onreadystatechange = function() {
    // check if request is complete
    if (this.readyState == this.DONE) {
        if (this.onreadystatechange) {
            delete client.onreadystatechange;
            handler();
        }
    }
};*/
		
			var resp = this.responseText;
			if (resp) {
				var websites = resp.split("\r\n");
				
				chrome.extension.onMessage.addListener(
					function(request, sender, sendResponse) {
						if (request.message == "website_data") {
							sendResponse({
								websites: websites
							});
						}
					}
				);
			}
		}
	}

	doUrlRequest("url_list.properties", onWebsiteDataRetrieval);
}

chrome.extension.onMessage.addListener(
	function(request, sender, sendResponse) {
		if (request.message == "getLongifiedUrls") {
			console.log('here');
			console.log(request.encodedLinksRequest);
			
			doUrlRequest(request.encodedLinksRequest.url, function() {
				if (xhr.readyState == 4 && xhr.status == 200)
				{
					var json = JSON.parse(this.responseText);
					
					for (var i = 0; i < encodedLinks.length; i++) {
						if (encodedLinks[i].innerText === encodedLinks[i].href) {
							encodedLinks[i].innerText = json[encodedLinks[i].href];
						}
						
						encodedLinks[i].href = json[encodedLinks[i].href];
					}
				}
			});
			
			//sendResponse(encodedLinksRequest);
		}
	}
);

parseWebsites();
